package controllers

import (
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	httpfacades "github.com/hulutech-web/http_result"
	"github.com/spf13/cast"
	"goravel/app/models"
)

type SearchCommentController struct {
	//Dependent services
}

func NewSearchCommentController() *SearchCommentController {
	return &SearchCommentController{
		//Inject services
	}
}

func (r *SearchCommentController) Index(ctx http.Context) http.Response {
	searchComments := []models.SearchComment{}
	queries := ctx.Request().Queries()
	result, _ := httpfacades.NewResult(ctx).SearchByParams(queries).ResultPagination(&searchComments, "SearchFilter", "CommentFilter")
	return result
}

// 组合列表
func (r *SearchCommentController) List(ctx http.Context) http.Response {
	searchComments := []models.SearchComment{}
	facades.Orm().Query().Model(&models.SearchComment{}).With("SearchFilter").With("CommentFilter").Find(&searchComments)
	return httpfacades.NewResult(ctx).Success("", searchComments)
}

// 组合
func (r *SearchCommentController) Combine(ctx http.Context) http.Response {
	SearchFilterID := ctx.Request().InputInt("search_filter_id")
	CommentFilterID := ctx.Request().InputInt("comment_filter_id")
	if SearchFilterID == 0 || CommentFilterID == 0 {
		return httpfacades.NewResult(ctx).Error(http.StatusInternalServerError, "组合参数错误", nil)
	}
	searchComment := models.SearchComment{}
	searchComment.SearchFilterID = cast.ToUint(SearchFilterID)
	searchComment.CommentFilterID = cast.ToUint(CommentFilterID)
	var exist bool
	facades.Orm().Query().Model(&models.SearchComment{}).Where("search_filter_id = ? AND comment_filter_id = ?", SearchFilterID, CommentFilterID).Exists(&exist)
	if exist {
		return httpfacades.NewResult(ctx).Error(http.StatusInternalServerError, "组合已存在", nil)
	}
	facades.Orm().Query().Model(&searchComment).Create(&searchComment)
	return httpfacades.NewResult(ctx).Success("组合成功", nil)
}

// 分离组合
func (r *SearchCommentController) Separate(ctx http.Context) http.Response {
	SearchFilterID := ctx.Request().InputInt("search_filter_id")
	CommentFilterID := ctx.Request().InputInt("comment_filter_id")
	searchComment := models.SearchComment{}
	facades.Orm().Query().Model(&models.SearchComment{}).Where("search_filter_id = ? AND comment_filter_id = ?", SearchFilterID, CommentFilterID).Find(&searchComment)
	if searchComment.ID == 0 {
		return httpfacades.NewResult(ctx).Error(http.StatusInternalServerError, "组合不存在", nil)
	}
	facades.Orm().Query().Model(&models.SearchComment{}).Where("search_filter_id = ? AND comment_filter_id = ?", SearchFilterID, CommentFilterID).Delete(&searchComment, []uint{searchComment.ID})
	return httpfacades.NewResult(ctx).Success("分离组合成功", nil)
}
